#include "queue.h"



#define TIMEOUT_INFINITE 0

void message_queue_insert(uint8 location,AF_message*message_content,uint8 timeout,uint16 dst_addr,uint8 from_source);
uint8 message_query(void);

typedef struct {
	uint8 node_num;
	uint8 queue_used[QUEUE_MAX];
}queue_node;

queue_node node;

message_queue net_message_queue[QUEUE_MAX];

void message_queue_init(void)
{
	uint8 i;
	for(i=0;i<QUEUE_MAX;i++)
	{
		net_message_queue[i].status=MESSAGE_FAIL;
		net_message_queue[i].timeout=TIMEOUT_INFINITE;
		net_message_queue[i].message_content=NULL;
		net_message_queue[i].from_source=0xFF;
		net_message_queue[i].dst_addr=0xFFFF;
		node.queue_used[i]=0;
	}
	node.node_num=0;
}
uint8 message_queue_register(AF_message*message_content,uint16 dst_addr,uint8 from_source)
{
	uint8 tmp=message_query();
	if(tmp<QUEUE_MAX)
	{
		message_content->message_location=tmp;
		message_queue_insert(tmp,message_content,2,dst_addr,from_source);
		return 1;
	}
	else
	{
		return 0;
		//error or full queue
	}
}
void message_queue_insert(uint8 location,AF_message*message_content,uint8 timeout,uint16 dst_addr,uint8 from_source)
{
	net_message_queue[location].status=MESSAGE_WAIT;
	net_message_queue[location].message_content=message_content;
	net_message_queue[location].timeout=timeout;
	net_message_queue[location].from_source=from_source;
	net_message_queue[location].dst_addr=dst_addr;
	net_message_queue[location].message_id=message_content->message_id;
	message_content->sum=message_content->content_type+message_content->message_content1+message_content->message_content2+message_content->message_content3+message_content->message_location+message_content->message_id;
	node.node_num++;
	if(node.node_num<QUEUE_MAX )
		node.queue_used[location]=1;
}
uint8 message_query(void)
{
	uint8 unused=0;
	while(node.queue_used[unused]!=0)
	{
		unused++;
	}
	return unused;
}

void del_mesaage_poor(uint8 location)
{
  if(node.node_num<1)return;
  net_message_queue[location].status=MESSAGE_FAIL;
  net_message_queue[location].message_content=NULL;
  net_message_queue[location].timeout=TIMEOUT_INFINITE;
  net_message_queue[location].from_source=0xFF;
  net_message_queue[location].dst_addr=0xFFFF;
  node.node_num--;
  node.queue_used[location]=0;
}
